// log_viewer_dialog.dart
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_deer/util/log/text_channel_system.dart';
import 'package:get/get.dart';

class LogViewerDialog extends StatefulWidget {
  const LogViewerDialog({super.key});

  @override
  State<LogViewerDialog> createState() => _LogViewerDialogState();
}

class _LogViewerDialogState extends State<LogViewerDialog> {
  late ScrollController _verticalController;
  late ScrollController _horizontalController;
  late ScrollController _channelListController;
  late TextChannelSystem channelSystem;

  double _textScaleFactor = 1.0;
  bool _atBottom = true;

  @override
  void initState() {
    super.initState();
    channelSystem = TextChannelSystem.instance;

    _verticalController = ScrollController();
    _horizontalController = ScrollController();
    _channelListController = ScrollController();

    // 监听垂直滚动位置
    _verticalController.addListener(_scrollListener);
  }

  void _scrollListener() {
    if (_verticalController.hasClients) {
      final maxScroll = _verticalController.position.maxScrollExtent;
      final currentScroll = _verticalController.position.pixels;
      setState(() {
        _atBottom = currentScroll >= maxScroll - 20; // 允许20像素误差
      });
    }
  }

  void _copyAllText() {
    final selectedChannel = channelSystem.selectedChannel;
    if (selectedChannel.isEmpty) return;

    final lines = channelSystem.getChannelLines(selectedChannel);
    if (lines == null) return;

    final allText = lines.join('\n');
    Clipboard.setData(ClipboardData(text: allText));
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('已复制全部文本到剪贴板')),
    );
  }

  @override
  void dispose() {
    _verticalController.removeListener(_scrollListener);
    _verticalController.dispose();
    _horizontalController.dispose();
    _channelListController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      // shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
      child: Container(
        width: MediaQuery.of(context).size.width * 0.9,
        height: MediaQuery.of(context).size.height * 0.8,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(4),
          // color: Colors.white,
        ),
        child: Column(
          children: [
            _buildHeader(),
            Expanded(child: _buildContent()),
            _buildFooter(),
          ],
        ),
      ),
    );
  }

  Widget _buildHeader() {
    return Container(
      padding: const EdgeInsets.only(left: 16, right: 6, top: 3, bottom: 3),
      decoration: const BoxDecoration(
        color: Colors.blue,
        borderRadius: BorderRadius.vertical(top: Radius.circular(4)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          const Text('日志查看器', style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold)),
          IconButton(icon: const Icon(Icons.close, color: Colors.white), onPressed: () => Navigator.of(context).pop()),
        ],
      ),
    );
  }

  Widget _buildContent() {
    return Row(
      children: [
        // 左侧频道列表
        Container(
          width: 150,
          decoration: const BoxDecoration(
            border: Border(right: BorderSide(color: Colors.grey)),
          ),
          child: Obx(() {
            final channels = channelSystem.channels;
            if (channels.isEmpty) {
              return const Center(child: Text('无频道'));
            }

            return ListView.builder(
              controller: _channelListController,
              itemCount: channels.length,
              itemBuilder: (context, index) {
                final channel = channels[index];
                return ListTile(
                  title: Text(channel, style: TextStyle(color: channelSystem.selectedChannel == channel ? Colors.blue : Colors.black)),
                  selected: channelSystem.selectedChannel == channel,
                  onTap: () {
                    channelSystem.selectedChannel = channel;
                    // 强制刷新状态
                    setState(() {});
                  },
                  dense: true,
                );
              },
            );
          }),
        ),

        // 右侧内容区域
        Expanded(
          child: Container(
            // decoration: const BoxDecoration(border: Border(left: BorderSide(color: Colors.grey))),
            child: _buildLogContent(),
          ),
        ),
      ],
    );
  }

  Widget _buildLogContent() {
    return Obx(() {
      final selectedChannel = channelSystem.selectedChannel;
      if (selectedChannel.isEmpty) {
        return const Center(child: Text('请选择频道'));
      }

      final lines = channelSystem.getChannelLines(selectedChannel);
      if (lines == null || lines.isEmpty) {
        return const Center(child: Text('暂无日志'));
      }

      // 自动滚动到底部
      if (channelSystem.autoScroll && _atBottom) {
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (_verticalController.hasClients) {
            _verticalController.animateTo(
              _verticalController.position.maxScrollExtent,
              duration: const Duration(milliseconds: 100),
              curve: Curves.easeOut,
            );
          }
        });
      }

      return Scrollbar(
        controller: _verticalController,
        child: SingleChildScrollView(
          controller: _horizontalController,
          scrollDirection: Axis.horizontal,
          child: ConstrainedBox(
            constraints: BoxConstraints(
              minWidth: MediaQuery.of(context).size.width - 150,
            ),
            child: SingleChildScrollView(
              controller: _verticalController,
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: lines
                      .map((line) => SelectableText(
                            line,
                            style: TextStyle(
                              fontFamily: 'monospace',
                              fontSize: 14 * _textScaleFactor,
                            ),
                          ))
                      .toList(),
                ),
              ),
            ),
          ),
        ),
      );
    });
  }

  Widget _buildFooter() {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      decoration: const BoxDecoration(
        border: Border(top: BorderSide(color: Colors.grey)),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              IconButton(
                icon: Icon(
                  channelSystem.isPaused ? Icons.play_arrow : Icons.pause,
                ),
                onPressed: () {
                  channelSystem.isPaused = !channelSystem.isPaused;
                },
                tooltip: channelSystem.isPaused ? '继续' : '暂停',
              ),
              IconButton(
                icon: Icon(
                  _atBottom ? Icons.keyboard_double_arrow_down  : Icons.keyboard_double_arrow_down_sharp,
                ),
                onPressed: () {
                  if (_verticalController.hasClients) {
                    _verticalController.animateTo(
                      _verticalController.position.maxScrollExtent,
                      duration: const Duration(milliseconds: 300),
                      curve: Curves.easeInOut,
                    );
                  }
                },
                tooltip: '滚动到底部',
              ),
              IconButton(
                icon: const Icon(Icons.delete),
                onPressed: () {
                  final selectedChannel = channelSystem.selectedChannel;
                  if (selectedChannel.isNotEmpty) {
                    channelSystem.clearChannel(selectedChannel);
                  }
                },
                tooltip: '清空当前频道',
              ),
              // 添加复制按钮
              IconButton(
                icon: const Icon(Icons.copy),
                onPressed: _copyAllText,
                tooltip: '复制全部文本',
              ),
            ],
          ),
          Row(
            children: [
              IconButton(
                icon: const Icon(Icons.remove),
                onPressed: () {
                  setState(() {
                    _textScaleFactor = (_textScaleFactor - 0.1).clamp(0.5, 3.0);
                  });
                },
                tooltip: '缩小字体',
              ),
              IconButton(
                icon: const Icon(Icons.add),
                onPressed: () {
                  setState(() {
                    _textScaleFactor = (_textScaleFactor + 0.1).clamp(0.5, 3.0);
                  });
                },
                tooltip: '放大字体',
              ),
              Text(
                '${(_textScaleFactor * 100).toInt()}%',
                style: const TextStyle(fontSize: 12),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
